package com.school.information.controller;

import com.school.information.utils.FileUtil;
import com.school.information.utils.ResultUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("file")
@Slf4j
public class FileController {
    private static final String QUESTION_TEMPLATE = "question.xlsx";

    @Value("${file.path}")
    private String filePath;
    @Value("${file.template.path}")
    private String templatePath;

    @PostMapping("/upload")
    public ResultUtil uploadSingleFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultUtil.ERROR_ARG;
        }
        String fileName = FileUtil.uploadSingleFilePath(file, filePath);
        log.info("##fileName=" + fileName);
        return ResultUtil.success(fileName);
    }

    @GetMapping("/export")
    public void downloadExcelTemplate(HttpServletResponse response, HttpServletRequest request) throws IOException {
//        log.info("##模板下载路径={}", templatePath + QUESTION_TEMPLATE);
//        BufferedInputStream bis = null;
//        try (
//                ServletOutputStream out = response.getOutputStream();
//                BufferedOutputStream bos = new BufferedOutputStream(out);
//        ){
//            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            wb.write(os);
//            byte[] content = os.toByteArray();
//
//            InputStream is = new ByteArrayInputStream(content);
//            // 设置response参数，可以打开下载页面
//            res.reset();
//            res.setContentType("application/vnd.ms-excel;charset=utf-8");
//            res.setHeader("Content-Disposition",
//                    "attachment;filename=" + new String(name.getBytes(), "iso-8859-1"));
//
//
//            bis = new BufferedInputStream(is);
//            byte[] buff = new byte[2048];
//            int bytesRead;
//            // Simple read/write loop.
//            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
//                bos.write(buff, 0, bytesRead);
//            }
//        } catch (Exception e) {
////			log.info(e.getMessage());
//        } finally {
//            try {
//                if (bis != null)
//                    bis.close();
//            }catch (IOException e){
////				log.info(e.getMessage());
//            }
//        }
    }
}
